package com.cyyang.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cyyang.bean.Cart;
import com.cyyang.bean.CartVo;
import com.cyyang.bean.HgUser;
import com.cyyang.service.UserService;



@Controller
public class UserController {
	
	@Reference
	UserService userService;
	
	@RequestMapping("toCart")
	public String toCart(HttpServletRequest req) {
		//根据用户的id查询用户下的购物车列表
		HgUser sessionUser = (HgUser) req.getSession().getAttribute("hg_user");
		if(sessionUser!=null) {
			List<Cart> carts = userService.findCartListByUid(sessionUser);
			req.setAttribute("carts", carts);
			return "cart";
		}
		return "redirect:toLogin";
	}
	
	@RequestMapping("addCard")
	@ResponseBody
	public String addCard(CartVo vo,HttpServletRequest req ) {
		try {
			System.out.println(vo);
			HgUser sessonUser = (HgUser) req.getSession().getAttribute("hg_user");
			if(sessonUser!=null) {
				vo.setUid(sessonUser.getUid());
				userService.addCart(vo);
				return "success!!!";
			}
			return "nologin";
		} catch (Exception e) {
			e.printStackTrace();
			return "fail";
		}
	}

	@RequestMapping("toLogin")
	public String toLogin() {
		return "login";
	}
	
	@RequestMapping("login")
	public String login(HgUser user,HttpServletRequest req,Model m) {
		HgUser dbUser = userService.login(user);
		if(dbUser!=null) {
			//登录成功
			req.getSession().setAttribute("hg_user", dbUser);
			return "redirect:/";
		}
		m.addAttribute("msg", "用户名或者密码有误,请重试");
		return "login";
	}
}
